﻿using System.Text;
using System.Threading.Tasks;
using MQTTnet;

namespace ConsoleApp
{
    internal class Program
    {

       static IMqttClient mMqttClient;
        /// <summary>
        /// 
        /// </summary>
        public static async Task Start()
        {
            MqttClientFactory mqttFactory = new MqttClientFactory();

           
            //使用Build构建
            var clientId = Guid.NewGuid().ToString("N");
            var mqttClientOptions = new MqttClientOptionsBuilder()
                .WithTcpServer("121.40.194.180", 1883)
                .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
                .WithClientId(clientId)
                .WithCleanSession(false)
                .WithKeepAlivePeriod(TimeSpan.FromSeconds(30))
                .WithCredentials("njsnh", "njsnh@2024")
                .Build();

             mMqttClient = mqttFactory.CreateMqttClient();
            //与3.1对比，事件订阅名称和接口已经变化
            mMqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;
            mMqttClient.ConnectedAsync += MqttClient_ConnectedAsync;
            mMqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
           await mMqttClient.ConnectAsync(mqttClientOptions);


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private static Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            Console.WriteLine("MqttClient_ApplicationMessageReceivedAsync");

            string message = Encoding.UTF8.GetString(arg.ApplicationMessage.Payload);

            System.IO.File.AppendAllLines("D:\\log.txt", new string[] { arg.ApplicationMessage.Topic + ":" + message });
            return Task.CompletedTask;
        }

        private static async Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        {
            Console.WriteLine("MqttClient_ConnectedAsync");

            await mMqttClient.SubscribeAsync("njyy/yydev/up/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce);

            await mMqttClient.SubscribeAsync("njyy/ztnjbz/up/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce);

        }

        private static async Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            Console.WriteLine("MqttClient_DisconnectedAsync");
            System.Threading.Thread.Sleep(180000);

            await Start();

        }

        static async Task Main(string[] args)
        {
          await  Start();

            while (true)
            {
                Console.ReadLine();
            }
           
        }
    }
}
